package top.ffhome.concurrent.beautiful.ch01;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class Demo1Test {
    private static final Log log = LogFactory.get();

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread threadA = new Thread(() -> {
            try {
                //  获取resourceA锁
                synchronized (resourceA) {
                    log.info("threadA get resourceA lock");
                    // 获取resourceB锁
                    synchronized (resourceB) {
                        log.info("threadA get resourceB lock");
                        //  释放resourceA锁
                        log.info("threadA release resourceA lock");
                        resourceA.wait();
                    }
                }
            } catch (InterruptedException e) {
                log.error(e);
            }
        });

        Thread threadB = new Thread(() -> {
            try {
                Thread.sleep(1000);
                //  获取resourceA锁
                synchronized (resourceA) {
                    log.info("threadB get resourceA lock");
                    log.info("threadB try get resourceB lock");
                    // 获取resourceB锁
                    synchronized (resourceB) {
                        log.info("threadB get resourceB lock");
                        //  释放resourceA锁
                        log.info("threadB release resourceA lock");
                        resourceA.wait();
                    }
                }
            } catch (InterruptedException e) {
                log.error(e);
            }
        });

        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();
        log.info("main thread end");
    }
}
